package com.codermn.day721.udptest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author jxau_scf
 * @date 2021/7/22 - 9:39
 */
public class Receiver extends JFrame implements ActionListener,Runnable{  //实现动作监听和线程接口

    private Container con;

    private JTextField input;

    private JTextArea showMesseage;           //显示消息

    private JButton SendMes;

    private DatagramSocket client = new DatagramSocket(7845);//定义一个socket用于处理消息，并给个端口



    public Receiver() throws IOException{
        this.setTitle("接受方");
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setBounds(400, 300, 400, 300);
        this.setLayout(null);
        //基本属性设置

        con = this.getContentPane();
        input = new JTextField();
        showMesseage = new JTextArea();
        SendMes = new JButton("发送");
        //初始化组件
        con.add(SendMes);con.add(input);con.add(showMesseage);
        SendMes.setBounds(0, 0, 400, 40);
        showMesseage.setBounds(0, 40, 400, 200);
        showMesseage.disable();
        input.setBounds(0, 240, 400, 30);
        SendMes.addActionListener(this);    //此类实现了ActionListener直接将this作为参数



    }
    @Override
    public void actionPerformed(ActionEvent e) {   //重写的监听方法
        byte[] bytes = new byte[1024*8];

        try {
            DatagramPacket packet = new DatagramPacket(bytes, 1024*8);
            packet.setAddress(InetAddress.getByName("localhost"));   //触发按钮创建报文
            packet.setPort(11001);                                  //设置端口并放入输入框的数据
            packet.setData(input.getText().getBytes(),0,input.getText().getBytes().length);
            client.send(packet);                                    //发送报文
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            while(true) {                           //设置循环一直来接受客户端的消息
                byte[] bytes = new byte[1024*8];
                DatagramPacket packet = new DatagramPacket(bytes, 8*1024);
                client.receive(packet);            //接受客户端发送的报文
                String ss = packet.getAddress().getHostName()+ new String(packet.getData())+'\n';
                System.out.println(ss);
                showMesseage.append(ss);            //取出数据转化为字符串并放入窗体的文本域
            }

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        new Thread(new Receiver()).start();  //利用Thread创建对象并运行run方法
    }

}
